<template>
  <div class="login-box">
    <h2>固废数据统计</h2>
    <van-form @submit="onSubmit">
      <van-field
        v-model="formData.username"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="formData.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div class="flexBetween">
        <van-field
          v-model="formData.code"
          type="password"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </div>
      <div style="margin: 16px">
        <van-button
          :loading="loading"
          round
          block
          type="info"
          native-type="submit"
          >登 录</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { getCodeImg, login, getInfo } from "../utils/api";
export default {
  data() {
    return {
      formData: {
        username: "",
        password: "",
        code: "",
        uuid: "",
      },
      captchaEnabled: true,
      codeUrl: "",
      loading: false,
    };
  },
  created() {
    this.getCode();
  },
  mounted() {},
  methods: {
    async onSubmit(values) {
      this.loading = true;
      const { data } = await login(this.formData);
      if (data.code == 200) {
        this.loading = false;

        localStorage.setItem("token", data.token);
        this.$router.push({ path: "/" });
        this.getCompanyInfo();
      } else {
        Toast(data.msg);
      }
    },
    async getCode() {
      const { data } = await getCodeImg();
      this.captchaEnabled =
        data.captchaEnabled === undefined ? true : data.captchaEnabled;
      if (this.captchaEnabled) {
        this.codeUrl = "data:image/gif;base64," + data.img;
        this.formData.uuid = data.uuid;
      } else {
        Toast(data.msg);
      }
    },
    async getCompanyInfo() {
      const { data } = await getInfo();
      if (data.code == 200) {
        localStorage.setItem("useroBJ", JSON.stringify(data.user));
      } else {
        Toast(data.msg);
      }
    },
  },
};
</script>

<style lang="less">
.login-box {
  padding: 20px;
  margin-top: 30%;
  .van-field__label {
    font-size: 16px;
    color: #000;
  }
  .flexBetween {
    display: flex;
    justify-content: space-between;
  }
  .van-field__control {
    font-size: 16px;
  }
  .van-button--round {
    font-size: 20px;
  }
  .login-code-img {
    width: 100px;
  }
}
</style>
